package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;

import com.sky.vo.OrderVO;
import com.sky.webSocker.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
//    @Value("${sky.shop.address}")
//    private String shopAddress;
//
//    @Value("${sky.baidu.ak}")
//    private String ak;

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    WebSocketServer webSocketServer;
    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //地址是否传过来
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //该用户的购物车是否有商品
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> carts = shoppingCartMapper.list(cart);
        if (carts == null && carts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //增加一条订单记录
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(orders.UN_PAID);
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orderMapper.insert(orders);
        //增加n条订单明细记录
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : carts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetails);
        //封装OrderSubmitVo
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().
                orderNumber(orders.getNumber()).
                orderAmount(orders.getAmount()).
                orderTime(orders.getOrderTime()).build();
        //清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        return orderSubmitVO;
    }


    /**
     * 模拟支付,修改订单状态和支付状态还有结账时间,webSocket推送浏览器来单提醒
     */
    @Override
    public void updatePayOrderStatus() {
        //id是模拟动态给的
        Long id = getOrderIdByProperties("orderId.properties");
        Orders orders = Orders.builder().payStatus(1).status(2).checkoutTime(LocalDateTime.now()).id(id++).build();
        //webSocket推送来单提醒
         HashMap<String, Object> map = new HashMap<>();
         map.put("type",1);
         map.put("orderId",orders.getId());
         map.put("content","来单提醒:"+orders.getId());
         String json = JSON.toJSONString(map);
         webSocketServer.sendToAllClient(json);
        //动态改变下一次orderId
        changeOrderIdByProperties("orderId.properties",id);
        orderMapper.update(orders);

    }

    /**
     * 修改properties文件的orderId(加一)
     * @param fileName
     * @param nextId
     */
    private void changeOrderIdByProperties(String fileName,Long nextId) {
        try {
            Properties properties = new Properties();
            //获得文件类加载路径
            ClassPathResource classPath = new ClassPathResource(fileName);
            File file = classPath.getFile();
            //加载文件
            properties.load(new FileInputStream(file));
            //将下一个id写进去
            properties.setProperty("id",nextId.toString());
            properties.store(new FileOutputStream(file),null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得properties文件的orderId
     * @param fileName
     * @return
     */
    public Long getOrderIdByProperties(String fileName)
    {
       Long id=null;
        try {
            Properties properties = new Properties();
            //获得文件类加载路径
            ClassPathResource classPath = new ClassPathResource(fileName);
            File file = classPath.getFile();
            //加载文件
            properties.load(new FileInputStream(file));
              id = Long.valueOf(properties.getProperty("id"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回orderId
        return  id;
    }

    /**
     * 订单条件分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        //部分订单需要菜品信息orderDishes
        List<OrderVO> orderVOS = getOrderVoList(page);
        return new PageResult(page.getTotal(), orderVOS);
    }

    /**
     * Orders转换为OrderVo
     *
     * @param page
     * @return
     */
    private List<OrderVO> getOrderVoList(Page<Orders> page) {
        List<Orders> orders = page.getResult();
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orders)) {
            for (Orders order : orders) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                List<OrderDetail> details = orderDetailMapper.getDetailById(order.getId());
                String orderDishes = getDishString(details);
                orderVO.setOrderDishes(orderDishes);
                orderVOS.add(orderVO);
            }
        }
        return orderVOS;
    }

    /**
     * 获得订单菜品信息字符串
     * @param details
     * @return
     */

    private String getDishString(List<OrderDetail> details) {
         List<String> list= details.stream().map(d -> {
            String s = d.getName() + "*" + d.getNumber();
            return s;
        }).collect(Collectors.toList());
         return String.join("",list);
    }


    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
         //待接单数量
         Integer toBeConfirmed=0;
         //待派送数量
         Integer confirmed=0;
         //派送中数量
         Integer deliveryInProgress=0;

        //先把所有订单找出来,然后增量添加
       List<Orders> orders= orderMapper.list();
        for (Orders order : orders) {
             Integer status = order.getStatus();
            switch (status)
            {
                case 2:
                    toBeConfirmed++;
                    break;
                case 3:
                    confirmed++;
                    break;
                case 4:
                    deliveryInProgress++;
                    break;
            }
        }
        //封装OrderStatisticsVO对象
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        statisticsVO.setConfirmed(confirmed);
        statisticsVO.setDeliveryInProgress(deliveryInProgress);
        statisticsVO.setToBeConfirmed(toBeConfirmed);
        return statisticsVO;
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderWithOrderDetailsByOrderId(Long id) {
        //查询对应订单
        Orders orders= orderMapper.getById(id);
        //查询该订单对应的订单详情
       List<OrderDetail> orderDetails= orderDetailMapper.getDetailById(id);
        //封装OrdersDTO
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder().status(Orders.CONFIRMED).id(ordersConfirmDTO.getId()).build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
         Orders orders= orderMapper.getById(ordersRejectionDTO.getId());
         //订单状态为2(待接单)时才可以退单
        if (orders==null||!orders.getStatus().equals(Orders.TO_BE_CONFIRMED))
        {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 拒单需要退款(这里简单模拟,修改数据库订单状态)
        Integer payStatus = orders.getPayStatus();
        Orders o= new Orders();
        if (payStatus==Orders.PAID)
        {
            //设置支付状态为退款
           o.setPayStatus(2);
        }
        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        o.setStatus(Orders.CANCELLED);
        o.setId(ordersRejectionDTO.getId());
        o.setCancelTime(LocalDateTime.now());
        o.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(o);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders= orderMapper.getById(ordersCancelDTO.getId());
        // 取消订单需要退款(这里简单模拟,修改数据库订单状态)
        Integer payStatus = orders.getPayStatus();
        Orders o= new Orders();
        if (payStatus==1)
        {
            //设置支付状态为退款
            o.setPayStatus(2);
        }
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        o.setStatus(Orders.CANCELLED);
        o.setId(ordersCancelDTO.getId());
        o.setCancelTime(LocalDateTime.now());
        o.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(o);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders= Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders= Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(orders);
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();
        List<Orders> orders = page.getResult();
        for (Orders order : orders) {
            // 查询订单明细
            List<OrderDetail> details = orderDetailMapper.getDetailById(order.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
           orderVO.setOrderDetailList(details);
           list.add(orderVO);
        }
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
         Orders orders= orderMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getDetailById(id);
       OrderVO orderVO = new OrderVO();
       BeanUtils.copyProperties(orders,orderVO);
       orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单(模拟退款,修改数据库支付状态)
     * @param id
     */
    @Override
    public void userCancelById(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailById(id);
        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
       Orders orders = orderMapper.getById(id);
       if (orders==null)
       {
           throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
       }

       //webSocker推送
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","催单提醒:"+orders.getId());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }


//    /**
//     * 检查客户的收货地址是否超出配送范围
//     * @param address
//     */
//    private void checkOutOfRange(String address) {
//        Map map = new HashMap();
//        map.put("address",shopAddress);
//        map.put("output","json");
//        map.put("ak",ak);
//
//        //获取店铺的经纬度坐标
//        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//
//        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
//        if(!jsonObject.getString("status").equals("0")){
//            throw new OrderBusinessException("店铺地址解析失败");
//        }
//
//        //数据解析
//        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
//        String lat = location.getString("lat");
//        String lng = location.getString("lng");
//        //店铺经纬度坐标
//        String shopLngLat = lat + "," + lng;
//
//        map.put("address",address);
//        //获取用户收货地址的经纬度坐标
//        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//
//        jsonObject = JSON.parseObject(userCoordinate);
//        if(!jsonObject.getString("status").equals("0")){
//            throw new OrderBusinessException("收货地址解析失败");
//        }
//
//        //数据解析
//        location = jsonObject.getJSONObject("result").getJSONObject("location");
//        lat = location.getString("lat");
//        lng = location.getString("lng");
//        //用户收货地址经纬度坐标
//        String userLngLat = lat + "," + lng;
//
//        map.put("origin",shopLngLat);
//        map.put("destination",userLngLat);
//        map.put("steps_info","0");
//
//        //路线规划
//        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
//
//        jsonObject = JSON.parseObject(json);
//        if(!jsonObject.getString("status").equals("0")){
//            throw new OrderBusinessException("配送路线规划失败");
//        }
//
//        //数据解析
//        JSONObject result = jsonObject.getJSONObject("result");
//        JSONArray jsonArray = (JSONArray) result.get("routes");
//        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
//
//        if(distance > 5000){
//            //配送距离超过5000米
//            throw new OrderBusinessException("超出配送范围");
//        }
//    }

}
